package com.yu.crm.utils;

import com.whyxzz.arcface.ArcFace;
import com.yxzz.common.exception.GeneralException;
import com.yxzz.common.helper.ResourceConfigHelpers;
import cz.adamh.utils.NativeUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * 特征值工具类
 */
public class EigenValue {

    /**
     * 通过人脸地址生成特征值
     * @param imageFile
     * @return
     */
    public static byte[] extractFeatureImageUrl(String imageFile) {
        try {
            String filePath="/usr/lib";
            NativeUtils.setLibraryPath(filePath);
            ArcFace arcFace = initArcFace();

            ArcFace.FaceInfo faceInfo = new ArcFace.FaceInfo();

            String imgPath = temporaryFile(imageFile);
            System.out.println("=========="+imgPath);
            byte[] bytes = arcFace.extractFeature(imgPath,faceInfo);
            // 活体判断  0：非真人；1：真人； -1：不确定； -2:传入人脸数>1；
            System.out.println("============活体判断>>"+faceInfo.liveness+"=====年龄>>"+faceInfo.age);
            File file=new File(imgPath);
            file.delete();
            return bytes;
        } catch (Exception e) {
            if (e.getMessage().equals("no face detected!")) {
                throw new GeneralException("图片无效");
            }
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 网络url生成临时文件
     * @param url
     * @return
     */
    public static String temporaryFile(String url){
        String fileName = url.substring(url.lastIndexOf("/"));     //为下载的文件命名
        FileOutputStream fileOut = null;
        HttpURLConnection conn = null;
        InputStream inputStream = null;
        File file=new File(fileName.replace("/",""));
        try {
            // 建立链接
            URL httpUrl=new URL(url);
            conn=(HttpURLConnection) httpUrl.openConnection();
            //以Post方式提交表单，默认get方式
            conn.setRequestMethod("GET");
            conn.setDoInput(true);
            conn.setDoOutput(true);
            // post方式不能使用缓存
            conn.setUseCaches(false);
            //连接指定的资源
            conn.connect();
            //获取网络输入流
            inputStream=conn.getInputStream();
            BufferedInputStream bis = new BufferedInputStream(inputStream);
            //判断文件的保存路径后面是否以/结尾
            /*if (!filePath.endsWith("/")) {
                filePath += "/";
            }*/
            //写入到文件（注意文件保存路径的后面一定要加上文件的名称）
            fileOut = new FileOutputStream(file);
            BufferedOutputStream bos = new BufferedOutputStream(fileOut);

            byte[] buf = new byte[4096];
            int length = bis.read(buf);
            //保存文件
            while(length != -1){
                bos.write(buf, 0, length);
                length = bis.read(buf);
            }
            bos.close();
            bis.close();
            conn.disconnect();
        }catch (Exception e){
            e.printStackTrace();
        }
        return file.getAbsolutePath();
    }

    /**
     * 通过图片流生成特征值
     * @param file
     * @return
     */
    public static byte[] sendExtractFeatureFile(MultipartFile file) {
        try {
            String filePath="/usr/lib";
            NativeUtils.setLibraryPath(filePath);
            ArcFace arcFace = initArcFace();
            ArcFace.FaceInfo faceInfo = new ArcFace.FaceInfo();
            File file1 = MultipartFileToFile.multipartFileToFile(file);
            byte[] bytes = arcFace.extractFeature(file1.getAbsolutePath(),faceInfo);
            MultipartFileToFile.delteTempFile(file1);
            return bytes;
        } catch (Exception e) {
            if (e.getMessage().equals("no face detected!")) {
                throw new GeneralException("图片无效");
            }
            e.printStackTrace();
        }
        return null;
    }

    public static ArcFace initArcFace(){
        ArcFace arcFace =null;
        try {
            String appId = "HH88GmhUVcneQKd686emE9Jhr8h2Pu8prK87wHMU1Q9h";
            String sdkKey = "2853pRiTRFqjzKPT2UtLzCPzCzY8p4Wq8dgFMhjYNZne";
            arcFace = new ArcFace(appId, sdkKey);
        }catch (Exception e){
            e.printStackTrace();
        }
        return arcFace;
    }

    /**
     * 通过人脸地址生成特征值
     * @param imageFile
     * @return
     */
    public static byte[] extractFeature(String imageFile){
        try {
            String property = ResourceConfigHelpers.getProperty("wechat.gzhImg");
            int lastIndex = property.lastIndexOf("/");
            if(lastIndex == - 1){
                System.out.println("没有找到字符串 / ");
            }else{
                System.out.println(" / 字符串最后出现的位置： "+ lastIndex);
                System.out.println("============"+imageFile);
                System.out.println("============"+property.substring(0,lastIndex));
                System.out.println("============"+imageFile.substring(property.indexOf(property.substring(lastIndex))+9));
                String url=property.substring(0,lastIndex)+imageFile.substring(property.indexOf(property.substring(lastIndex))+9);

                NativeUtils.setLibraryPath("/usr/lib/");
                String appId = "HH88GmhUVcneQKd686emE9Jhr8h2Pu8prK87wHMU1Q9h";
                String sdkKey = "2853pRiTRFqjzKPT2UtLzCPzCzY8p4Wq8dgFMhjYNZne";
                ArcFace arcFace = null;
                arcFace = new ArcFace(appId, sdkKey);
                ArcFace.FaceInfo faceInfo = new ArcFace.FaceInfo();
                return arcFace.extractFeature(url,faceInfo);
            }
        }catch (Exception e){
            if(e.getMessage().equals("no face detected!")){
                throw new GeneralException("图片无效");
            }
            e.printStackTrace();
        }
        return null;
       /* try {
            System.out.println(System.getProperty("java.library.path"));
            NativeUtils.setLibraryPath("/usr/lib/");
            System.out.println(System.getProperty("java.library.path"));
        } catch (Exception var10) {
        }

        String appId = "HH88GmhUVcneQKd686emE9Jhr8h2Pu8prK87wHMU1Q9h";
        String sdkKey = "2853pRiTRFqjzKPT2UtLzCPzCzY8p4Wq8dgFMhjYNZne";
        ArcFace arcFace = null;
        try {
            arcFace = new ArcFace(appId, sdkKey);
            return arcFace.extractFeature(imageFile,faceInfo);
        } catch (Exception var7) {
            var7.printStackTrace();
        } finally {
            if (arcFace != null) {
                arcFace.release();
            }
        }

        return null;*/
    }

    /*public static void main(String[] args) {
        String strOrig = "/home/whyxzz/web/fkxt/person_img";
        String strOrig1 = "http://fkgzh.whyxzz.net/person_img/201908/6b9b2e4ef65740539411c7709ba065bb.jpg";
        int lastIndex = strOrig.lastIndexOf("/");
        if(lastIndex == - 1){
            System.out.println("没有找到字符串 Runoob");
        }else{
            System.out.println("Runoob 字符串最后出现的位置： "+ lastIndex);
            System.out.println("============"+strOrig.substring(lastIndex));
            System.out.println("============"+strOrig.substring(0,lastIndex));
            System.out.println("============"+strOrig1.substring(strOrig.indexOf(strOrig.substring(lastIndex))+2));
            System.out.println("============"+strOrig.substring(0,lastIndex)+strOrig1.substring(strOrig.indexOf(strOrig.substring(lastIndex))+2));

        }
    }*/
}
